package com.gec.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.gec.dao.OrderDao;
import com.gec.dao.OrderItemDao;
import com.gec.entity.Cart;
import com.gec.entity.CartItem;
import com.gec.entity.Order;
import com.gec.entity.OrderItem;
import com.gec.entity.User;

@WebServlet("/QueDingOrderServlet")
public class QueDingOrderServlet extends HttpServlet{
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	    //取出所有提交过来的参数信息
	    HttpSession session = request.getSession();
    String oid=request.getParameter("oid");
    String address=request.getParameter("address");
    String name=request.getParameter("name");
    String telephone=request.getParameter("telephone");
    
    OrderDao orderDao = new OrderDao();
    OrderItemDao orderItemDao = new OrderItemDao();
    
    User user = (User)session.getAttribute("user");
    
    Order order=new Order();
    order.setOid(oid);
    order.setUid(user.getUid());  //设置购买人信息
    order.setAddress(address);
    order.setName(name);
    order.setTelephone(telephone);
    order.setState(0);
    
    
  //将购物车中的商品都取出来 然后放到订单类中
    List<OrderItem> orderItems = new ArrayList<OrderItem>();
    
    //从hashmap中取出购物车的商品信息
    Cart cart = (Cart) session.getAttribute("cart");
    Set<Entry<String, CartItem>> entry = cart.getCartItems().entrySet();
    
    for (Entry<String, CartItem> cartItem : entry) {
	OrderItem orderItem = new OrderItem();
	orderItem.setItemId(UUID.randomUUID().toString());
	orderItem.setCount(cartItem.getValue().getBuyNum());
	orderItem.setOid(order.getOid());
	orderItem.setProduct(cartItem.getValue().getProduct());
	orderItems.add(orderItem);
	
	
    }
    order.setOrderItems(orderItems);
	orderDao.addOrder(order); //将订单信息写入数据表中  一定要写在后面不然计算不了总价
    //将订单信息填入订单信息表中
    for(OrderItem o : orderItems){
        orderItemDao.addOrderItem(o);
    }    
    //清除购物车信息
    session.removeAttribute("cart");
    //获取订单中详细的商品信息
    request.setAttribute("order", order);
    request.getRequestDispatcher("account.jsp").forward(request, response);
}
	


}
